package com.alinesno.cloud.monitor.agent.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import cn.hutool.json.JSONUtil;

/**
 * 业务层方法执行监控 , AOP切面 ：多个切面时，@Order(i)注解来标识切面的优先级。i的值越小，优先级越高,看方法运行的时间 
 * @author LuoAnDong
 * @since 2019年4月8日 下午8:30:43
 */
@Order(5)
@Aspect
@Component
public class ServiceMethonRunningAspect {
	
    private static final Logger log = LoggerFactory.getLogger(ServiceMethonRunningAspect.class);

    @Pointcut("execution(public * com.alinesno.cloud.service..*.*(..))")
    public void method(){}
 
    //统计请求的处理时间
    ThreadLocal<Long> startTime = new ThreadLocal<>();
 
    @Before("method()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        startTime.set(System.currentTimeMillis());
    }
 
    @AfterReturning(returning = "ret" , pointcut = "method()")
    public void doAfterReturning(Object ret){
        //处理完请求后，返回内容
        log.debug("方法返回值:"+ JSONUtil.toJsonStr(ret) +",方法执行时间:"+ (System.currentTimeMillis() - startTime.get()));
    }
}


